import React, { Component } from 'react';
import { meshLog, SPRemove, SPGet, SPSet } from '../../../config';
import './ad.less';
import { insertAdInfo } from '../../../api/index.js';

export default class Ad extends Component {
  state = {
    imageName: '',
    selectedFile: null,
  };

  handleImageChange = (e) => {
    this.setState({ selectedFile: e.target.files[0] });
  };

  uploadImage = async () => {
    const { selectedFile } = this.state;
    if (!selectedFile) return alert('请选择图片');

    const formData = new FormData();
    formData.append('file', selectedFile);

    fetch('/upload_ad_image', {
      method: 'POST',
      body: formData,
    })
      .then(res => res.json())
      .then(data => {
        meshLog('data', data);
        if (data.code === 0) {
          // this.setState({ imageName: data.fileName });
          alert('上传成功');
        } else {
          alert('上传失败');
        }
      });


  };

  handleSubmit = async (e) => {
    e.preventDefault();
    const { imageName } = this.state;
    const formData = new FormData(e.target);
    formData.append('imageName', imageName);
    // 获取表单中的字段值
    const title = formData.get('title');
    const onClick = formData.get('textlink');
    // 打印到控制台
    console.log('广告标题:', title);
    console.log('跳转链接:', onClick);
    console.log('图片名称:', this.state.selectedFile.name);
    let img = '/images/game/banner/' + this.state.selectedFile.name
    meshLog('img', img);
    let result = await insertAdInfo(title, img, onClick)
    meshLog('result', result);

    if (result.code === 0) {
      alert("提交成功")
    } else {
      alert("提交失败")
    }

  };

  render() {
    const { imageName } = this.state;

    return (
      <div className="ad">
        <div className="addaohang">
          <span className="addaohangzuo">位置：智慧夜跑 》商业广告</span>
        </div>

        <div className="adneirong">
          <div className="ad-form-wrapper">
            <form onSubmit={this.handleSubmit} className="ad-form">
              <div className="form-row">
                <div className="form-group">
                  <label>广告图片：</label>
                  <input type="file" accept="image/*" onChange={this.handleImageChange} />
                  <button type="button" onClick={this.uploadImage}>上传</button>
                </div>
                <div className="form-group">
                  <label>广告标题：</label>
                  <input type="text" name="title" required />
                </div>
                <div className="form-group">
                  <label>跳转链接：</label>
                  <input type="text" name="textlink" />
                </div>
                <input type="hidden" name="imageName" value={imageName} />
              </div>
              <div className="form-submit-row">
                <button type="submit">提交</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    );
  }
}
